package com.chuqiyun.authorization.controller.user;

import com.alibaba.fastjson2.JSONObject;
import com.chuqiyun.authorization.annotation.ApiCheck;
import com.chuqiyun.authorization.entity.User;
import com.chuqiyun.authorization.service.UserService;
import com.chuqiyun.authorization.utils.EncryptUtil;
import com.chuqiyun.authorization.utils.JWTUtil;
import com.chuqiyun.authorization.utils.ResponseResult;
import com.chuqiyun.authorization.utils.ServletUtil;
import com.chuqiyun.authorization.utils.exception.UnauthorizedException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;
import java.util.UUID;

/**
 * @author mryunqi
 * @date 2023/4/16
 */
@RestController
public class UserAccountController {
    @Resource
    private UserService userService;

    @Value("${config.secret}")
    private String secret;

    /**
    * @Author: mryunqi
    * @Description: 普通用户登录接口
    * @DateTime: 2023/4/16 21:40
    * @Params: JSONObject param
    * @Return ResponseResult<String>
    */
    @PostMapping("/user/loginDo")
    public ResponseResult<String> userLoginDo(@RequestBody JSONObject param,
                                              HttpServletResponse response) throws UnauthorizedException {
        User existingUser = userService.getUser(param.getString("phone"));
        if (Objects.isNull(existingUser)){
            //判断用户是否存在
            return ResponseResult.fail(ResponseResult.RespCode.LOGIN_NO_ACCOUNT);
        }else if (!existingUser.getPassword().equals(EncryptUtil.md5(param.getString("password")))){
            //判断用户密码是否正确
            return ResponseResult.fail(ResponseResult.RespCode.LOGIN_FAIL);
        }
        Long nowDate = System.currentTimeMillis();
        existingUser.setLoginDate(nowDate);
        existingUser.updateById();
        String jwtToken = JWTUtil.sign(param.getString("phone"),secret);
        Cookie cookie = new Cookie("Authorization", jwtToken);
        // 120秒失效
        cookie.setMaxAge(7200);
        response.addCookie(cookie);
        return ResponseResult.ok(jwtToken);
    }


    @PostMapping("/user/registerDo")
    public ResponseResult<String> userRegisterDo(@RequestBody User user){
        User existingUser = userService.getUser(user.getPhone());
        if (!Objects.isNull(existingUser)){
            //判断用户是否存在
            return ResponseResult.fail(ResponseResult.RespCode.REG_EXISTING_USER);
        }
        Long nowDate = System.currentTimeMillis();
        user.setUuid(UUID.randomUUID().toString());
        user.setPassword(EncryptUtil.md5(user.getPassword()));
        user.setRegisterDate(nowDate);
        if (userService.save(user)) {
            return ResponseResult.ok("注册成功！");
        } else {
            return ResponseResult.fail("注册失败！");
        }
    }

    /**
    * @Author: mryunqi
    * @Description: 获取当前cookie的用户数据
    * @DateTime: 2023/4/19 22:43
    * @Return ResponseResult<User>
    */
    @ApiCheck
    @GetMapping("/user/getSelfInfo")
    public ResponseResult<User> getSelfInfo(HttpServletRequest request){
        User cookieUser = ServletUtil.getLoginMember(request,secret);
        assert cookieUser != null;
        User user = userService.getUser(cookieUser.getPhone());
        return ResponseResult.ok(user);
    }

    @ApiCheck
    @GetMapping("/user/getUserInfo")
    public ResponseResult<User> getUserInfo(@RequestParam(value ="phone") String phone){
        User user = userService.getUser(phone);
        return ResponseResult.ok(user);
    }
}
